package com.imooc.interceptor;

import com.imooc.constant.RedisConstant;
import com.imooc.controller.HelloController;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author gcq
 * @Create 2022-03-29
 */
public class UserTokenInterceptor implements HandlerInterceptor {

    final static Logger logger = LoggerFactory.getLogger(UserTokenInterceptor.class);

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 拦截请求 controller 访问之前
     *
     * 主要作用
     * 1、用户访问对应的接口是否有权限
     * 2、根据请求头携带的token获取用户信息，放到当前线程中
     *      headers、body
     * 3、记录接口访问信息等等
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 取出 userId 和 userToken
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        if(StringUtils.isBlank(userId) && StringUtils.isBlank(userToken)) {
            String uniqueToken = redisOperator.get(RedisConstant.REDIS_USER_TOKEN + userId);
            if(StringUtils.isBlank(uniqueToken)) {
                logger.error("=========================>请登录<=========================>");
                this.returnErrorResponse(response, IMOOCJSONResult.errorMsg("请登录"));
                return false;
            } else {
                if(!uniqueToken.equals(userToken)) {
                    logger.error("=========================>账号在异地登录<=========================>");
                    this.returnErrorResponse(response, IMOOCJSONResult.errorMsg("账号在异地登录"));
                    return false;
                }
            }
        } else {
            logger.error("=========================>请登录<=========================>");
            this.returnErrorResponse(response, IMOOCJSONResult.errorMsg("请登录"));
            return false;
        }

        return true;
    }


    /**
     * 通过 response 中的 outputStream 返回错误信息
     *
     * TODO 通过 ControllerAdvice 进行返回？
     * @param response
     * @param result
     */
    public void returnErrorResponse(HttpServletResponse response,
                                    IMOOCJSONResult result) {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 请求访问 controller 渲染视图之前，开始处理业务
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 请求访问 controller 渲染视图之后,业务处理完毕后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}